var IDMark_A = "_a",
    layerTransparent = {},
    cesium,
    viewerTerrain = false;

//显示图层控制器
$("#layerbar-main-form-data").click(function () {
    //show3DLayers(MapConfig.Layers);
    var ztreeconcet = document.getElementById("ztreecentent");
    if (ztreeconcet.style.display != 'block') {
        ztreeconcet.style.display = 'block';
    } else {
        ztreeconcet.style.display = 'none';
    }
});

function show3DLayersMap(layersconfig) {
    cesium = this;
    //if (!cesium.isLoad3DLayers) {
        //cesium.isLoad3DLayers = showLayersView();
    //}
    showLayersView();
    //显示图层控制器
    function showLayersView() {
        cesium.layer3DList = {};
        this.treeObj = null;
        //加载图层目录树
        InitTree();
        return true;
    }
    //初始化图层目录树
    function InitTree() {
        var setting = {
            view: {
                //addDiyDom: addDiyDom //普通滑块版本
            },
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onRightClick: OnRightClick, //右键菜单版本
                onCheck: function (e, treeId, treeNode) {
                    if (treeNode.checked) { //勾选状态下,显示地图控件
                        if (treeNode.children) { //勾选专题目录
                            loadServerTypeMapRecursive(treeNode);
                        } else { //勾选叶节点
                            if ($("#range_" + treeNode.id).length > 0) $("#range_" + treeNode.id).show()
                            loadServerTypeMap(treeNode);
                        }
                    } else { //去掉勾选框,隐藏地图控件
                        if (treeNode.children) { //专题目录
                            deleteServerTypeMapRecursive(treeNode);
                        } else { //叶节点
                            if ($("#range_" + treeNode.id).length > 0) $("#range_" + treeNode.id).hide()
                            deleteServerTypeMap(treeNode.id, treeNode.type);
                        }
                    }
                }
            }
        };
        var ztreeRoleAuth = $("#ztree");
        if ($.fn.zTree) {
            var ztree = $.fn.zTree.init(ztreeRoleAuth, setting, layersconfig);
            this.treeObj = $.fn.zTree.getZTreeObj("ztree");
            //this.treeObj.expandAll(true);
            //加载已经勾选的图层
            var nodes = this.treeObj.getCheckedNodes(true);
            if (nodes.length > 0) {
                for (var i = nodes.length - 1; i >= 0; i--) {
                    if (!nodes[i].isParent) { //节点图层
                        loadServerTypeMap(nodes[i]);
                    }
                }
                $("#mask-load").hide();
            }
        }
    }

    // 递归关闭图层
    function deleteServerTypeMapRecursive(treeNode) {
        for (var i = 0; i < treeNode.children.length; i++) {
            if (treeNode.children[i].children) {
                deleteServerTypeMapRecursive(treeNode.children[i]);
            } else {
                deleteServerTypeMap(treeNode.children[i].id, treeNode.children[i].type);
            }
        }
    }

    // 递归开启图层
    function loadServerTypeMapRecursive(treeNode) {
        for (var i = 0; i < treeNode.children.length; i++) {
            if (treeNode.children[i].children) {
                loadServerTypeMapRecursive(treeNode.children[i]);
            } else {
                loadServerTypeMap(treeNode.children[i]);
            }
        }
    }

    function addDiyDom(treeId, treeNode) {
        if (!treeNode.pId) return;
        //var aObj = $("#" + treeNode.tId + IDMark_A);
        var aObj = $("#" + treeNode.tId);
        if (treeNode.transparent) {
            var editStr = '<div id="range_' + treeNode.id + '" layerType="' + treeNode.type + '" style="display:inline-block;width: auto;min-width: 80px;"></div>';
            //var editStr = '<div style="display:inline-block;"><input layerType="' + treeNode.type + '" style="width: auto !important;display:inline-block;" value="100" type="range" id="range_' + treeNode.id + '" min="0" max="100" step="1.0" title="透明度"></input></div>';
            aObj.append(editStr);
            slider.render({
                elem: '#range_' + treeNode.id,
                //range: true,
                min: 0,
                max: 100,
                step: 1,
                value: 100,
                change: function (value) {
                    var layerId = parseInt(this.elem.split("_")[1]);
                    var layerType = parseInt($(this.elem)[0].attributes.layertype.value);
                    changeLayerTransparent(layerId, layerType, value / 100);
                }
            });
            var range = $("#range_" + treeNode.id);
            if (range) {
                if (!treeNode.checked) range.hide();
            }
        }
    }

    /**
     * 删除指定ID的图层
     */
    function deleteServerTypeMap(id, servertype) {
        switch (typeof (id)) {
            case "number":
                if (cesium.layer3DList[id]) {
                    if (servertype == 9) { //terrain
                        viewerTerrain = false;
                        viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
                    } else if (servertype == 10 || servertype == 16) { //3dtile //gltf
                        cesium.layer3DList[id].show = false;
                        //viewer.scene.primitives.remove(cesium.layer3DList[id])
                    } else if (servertype == 15) { //iServer
                        cesium.layer3DList[id].visible = false;
                        //viewer.scene.primitives.remove(cesium.layer3DList[id])
                    } else if (servertype == 7 || servertype == 11 || servertype == 12 || servertype == 13) { //geojson
                        var entities = cesium.layer3DList[id].entities.values;
                        for (var i = 0; i < entities.length; i++) {
                            entities[i].show = false;
                        }
                    } else { //image
                        viewer.scene.imageryLayers.remove(cesium.layer3DList[id]);
                        cesium.layer3DList[id] = null;
                    }
                }
                break;
            case "string":
                var len = viewer.dataSources.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        var dataSource = viewer.dataSources.get(i);
                        if (dataSource._name && dataSource._name == id) {
                            viewer.dataSources.remove(dataSource);
                        }
                    }
                }
                break;
            case "undefined":
                break;
        }
    }

    var geojsonPictureObj = {
        "classID": {
            1: "zhengfu.fw.png",
            2: "jingqu.png",
            3: "yiyuan.fw.png",
            4: "zhongxue.png",
            5: "daxue.fw.png",
            6: "dasha.png",
            7: "cheng.fw.png",
            8: "canting.png",
            9: "chaoshi.fw.png",
            10: "jiudian.png",
            11: "jiayouzhan.fw.png",
            12: "huochezhan.png",
            13: "gongjiao.fw.png",
            14: "yinhang.fw.png",
            24: "gongjiao.fw.png"
        }
    }

    function checkLayerTransparent(layer, id, alpha) {
        if (layerTransparent[id]) {
            layer.alpha = layerTransparent[id];
        } else if (alpha) {
            layer.alpha = alpha;
        }
    }

    /**
      * 加载不同类型地图服务的底图
      @ id 图层的id标识
      @ servertype 地图服务类型(0代表ArcGisMapServerImageryProvider;1代表createOpenStreetMapImageryProvider;
      2代表WebMapTileServiceImageryProvider;3代表createTileMapServiceImageryProvider;
      4 代表UrlTemplateImageryProvider;5 代表WebMapServiceImageryProviderr(WMS))
      @ url 地图服务的url
      @ layerid 地图图层的id
      @ proxyUrl 代理请求url
      @ tilingScheme 地图坐标系,WebMercatorTilingScheme(摩卡托投影坐标系3857);GeographicTilingScheme(世界地理坐标系4326)
      */
    function loadServerTypeMap(params) {
        var id = params.id;
        var servertype = params.type;
        var url = params.layerurl;
        var layerid = params.layerid;
        var proxyUrl = params.proxyUrl;
        var IsWebMercatorTilingScheme = params.IsWebMercatorTilingScheme;
        var layerindex = params.layerindex;
        var distance = params.distance;
        var labelField = params.labelField;
        var labelFont = params.labelFont;
        var labelColor = params.labelColor;
        var labelDistance = params.labelDistance;
        var labelHeight = params.labelHeight;
        var labelBackground = params.labelBackground;
        var billboard = params.billboard;
        var billboardSize = params.billboardSize;
        var billboardDistance = params.billboardDistance;
        var x = params.x;
        var y = params.y;
        var alpha = params.alpha;
        var maximumLevel = params.maximumLevel;
        var minimumLevel = params.minimumLevel;
        var outlineColor = params.outlineColor;
        var outlineWidth = params.outlineWidth;

        var layers = viewer.scene.imageryLayers;
        layerindex = layerindex > layers._layers.length ? layers._layers.length : layerindex;
        var curlayer = null;
        switch (servertype) {
            case 0: //ArcGisMapServerImageryProvider
                if (cesium.layer3DList[id]) {
                    return;
                }
                var curlayer = layers.addImageryProvider(new Cesium.ArcGisMapServerImageryProvider({
                    proxy: new Cesium.DefaultProxy(proxyUrl),
                    url: url
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 1: //OpenStreetMapImageryProvider
                if (cesium.layer3DList[id]) {
                    return;
                }
                var curlayer = layers.addImageryProvider(Cesium.createOpenStreetMapImageryProvider({
                    url: url
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 2: //WebMapTileServiceImageryProvider
                if (cesium.layer3DList[id]) {
                    return;
                }
                var subdomains = ['0', '1', '2', '3', '4', '5', '6', '7'];
                var curlayer = layers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({   
                    //影像注记
                    url: url + "&tk=" +  m_MapConfigLayers.tiandituTk,
                    subdomains: subdomains,
                    layer: layerid,
                    style: "default",
                    format: "image/jpeg",
                    tileMatrixSetID: "GoogleMapsCompatible",
                    show: true
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 3: //createTileMapServiceImageryProvider
                break;
            case 4: //UrlTemplateImageryProvider
                if (cesium.layer3DList[id]) {
                    return;
                }
                var curlayer = layers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                    url: url, //服务地址
                    maximumLevel: maximumLevel,
                    minimumLevel: minimumLevel ? minimumLevel : 0
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 5: //WebMapServiceImageryProvider  //WMS
                if (cesium.layer3DList[id]) {
                    return;
                }
                var m_tilingScheme = new Cesium.GeographicTilingScheme();
                if (IsWebMercatorTilingScheme) {
                    m_tilingScheme = new Cesium.WebMercatorTilingScheme();
                }
                var curlayer = layers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
                    url: url,
                    layers: layerid,
                    //tilingScheme:tilingScheme,
                    tilingScheme: m_tilingScheme,
                    parameters: {
                        service: "WMS",
                        version: "1.1.1",
                        request: "GetMap",
                        transparent: true,
                        format: 'image/png'
                    }
                    //show: false
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 6: //kml,kmz
                var options = {
                    camera: cesium.cesiumViewer.scene.camera,
                    canvas: cesium.cesiumViewer.scene.canvas
                };
                cesium.cesiumViewer.dataSources.add(Cesium.KmlDataSource.load(url, options)).then(function (dataSource) {
                    cesium.cesiumViewer.camera.flyHome();
                });
                break;
            case 7: //geoJson-billboard
                if (cesium.layer3DList[id]) {
                    var entities = cesium.layer3DList[id].entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        entities[i].show = true;
                    }
                    return
                }
                Cesium.GeoJsonDataSource.load(url).then(function (dataSource) {
                    var entities = dataSource.entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        var entity = entities[i];
                        entity.label = {
                            text: entity._properties.getValue("")[labelField],
                            font: labelFont,
                            fillColor: !labelColor ? Cesium.Color.WHITE : Cesium.Color.fromCssColorString(labelColor),
                            outlineColor: Cesium.Color.BLACK,
                            outlineWidth: 1,
                            showBackground: !labelBackground ? false : true,
                            backgroundColor: !labelBackground ? Cesium.Color.GREEN : Cesium.Color.fromCssColorString(labelBackground),
                            backgroundPadding: new Cesium.Cartesian2(3, 3),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            pixelOffset: new Cesium.Cartesian2(0, labelHeight),
                            disableDepthTestDistance: 200.0,
                            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, labelDistance)
                        };
                        var pictureSrc = geojsonPictureObj[billboard][entity._properties.getValue("")[billboard]] ? geojsonPictureObj[billboard][entity._properties.getValue("")[billboard]] : "default.png";
                        entity.billboard = {
                            image: "/img/picture/" + pictureSrc, // default: undefined
                            show: true, // default
                            pixelOffset: new Cesium.Cartesian2(0, 0), // default: (0, 0)
                            eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0), // default
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
                            verticalOrigin: Cesium.VerticalOrigin.CENTER, // default: CENTER
                            scale: 1.0, // default: 1.0
                            color: Cesium.Color.WHITE, // default: WHITE
                            //rotation: Cesium.Math.PI_OVER_FOUR, // default: 0.0
                            //alignedAxis: Cesium.Cartesian3.UNIT, // default
                            //distanceDisplayCondition: 100,
                            //scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.5, 8.0e6, 0.0),
                            width: billboardSize, // default: undefined
                            height: billboardSize, // default: undefined
                            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, billboardDistance)
                        };
                    }
                    curlayer = viewer.dataSources.add(dataSource);
                    //viewer.scene.primitives.add(dataSource);
                    cesium.layer3DList[id] = dataSource;
                });
                break;
            case 8: //wmts
                if (cesium.layer3DList[id]) {
                    return;
                }
                let matrixIds = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10',
                    'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'
                ];
                var curlayer = layers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
                    url: url,
                    layer: layerid,
                    style: '',
                    format: 'image/png',
                    tileMatrixLabels: matrixIds,
                    tileMatrixSetID: 'EPSG:4326', //一般使用EPSG:3857坐标系
                    tilingScheme: new Cesium.GeographicTilingScheme({
                        numberOfLevelZeroTilesX: 2,
                        numberOfLevelZeroTilesY: 1
                    })
                }), layerindex);
                checkLayerTransparent(curlayer, id, alpha);
                break;
            case 9: //terrainProvider
                var curlayer;
                if (url) {
                    curlayer = new Cesium.CesiumTerrainProvider({
                        url: url,
                        ellipsoid: viewer.scene.globe.ellipsoid
                        // requestVertexNormals: false,
                        // requestVertexNormals: true
                    });
                    // curlayer.availability = new Cesium.TileAvailability(new Cesium.TilingScheme({
                    //     ellipsoid : viewer.scene.globe.ellipsoid
                    // }), 19);
                } else {
                    curlayer = Cesium.createWorldTerrain({
                        requestWaterMask: false,
                        requestVertexNormals: false
                    });
                }
                viewer.scene.terrainProvider = curlayer;
                viewerTerrain = true;
                viewer.scene.globe.enableLighting = false;
                break;
            case 10: //Cesium3DTileset
                if (cesium.layer3DList[id]) {
                    cesium.layer3DList[id].show = true;
                    return
                }
                var tileset = new Cesium.Cesium3DTileset({
                    url: url,
                    maximumMemoryUsage: 2048 //tileset可以使用的最大内存量（以MB为单位）,默认512。
                    // minimumPixelSize: 128,
                    // maximumScale: 20000
                    // maximumScreenSpaceError: 4, //最大屏幕空间误差
                    //maximumNumberOfLoadedTiles: 100000 //最大加载瓦片个数
                });
                //创建平移矩阵方法
                // var translation = Cesium.Cartesian3.fromArray([118.702541775971990, 39.744978006820702, 21385.3142451793]);
                // var m = Cesium.Matrix4.fromTranslation(translation);
                // // //生效
                // tileset._modelMatrix = m;
                // tileset.modelMatrix = m;
                // var curlayer = viewer.scene.groundPrimitives.add(tileset);
                var curlayer = viewer.scene.primitives.add(tileset);
                //viewer.zoomTo(tileset);
                curlayer.readyPromise.then(function (tileset) {
                    var boundingSphere = tileset.boundingSphere;
                    var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center); //获取到倾斜数据中心点的经纬度坐标（弧度）
                    var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0); //倾斜数据中心点的笛卡尔坐标

                    if (distance) {
                        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, distance); //带高程的新笛卡尔坐标
                        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3()); //做差得到变换矩阵
                        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
                    } else if (viewer.terrainProvider) {
                        var positions = [Cesium.Cartographic.fromDegrees(cartographic.longitude, cartographic.latitude)];
                        var promise;
                        if (viewer.terrainProvider.availability) {
                            promise = Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, positions);
                        } else {
                            // promise = Cesium.sampleTerrain(viewer.terrainProvider, 19, [Cesium.Cartographic.fromCartesian(surface)]);
                            promise = Cesium.sampleTerrain(viewer.terrainProvider, 19, [new Cesium.Cartographic(cartographic.longitude, cartographic.latitude)]);
                        }
                        Cesium.when(promise, function (updatedPositions) {
                            if (updatedPositions[0].height) {
                                var terrainHeight = updatedPositions[0].height; //高程
                                var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, terrainHeight); //带高程的新笛卡尔坐标
                                var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3()); //做差得到变换矩阵
                                tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
                            }
                        });
                    }
                }).otherwise(function (error) {
                    console.log(error);
                });
                break;
            case 11: //geoJson-point-label
                if (cesium.layer3DList[id]) {
                    var entities = cesium.layer3DList[id].entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        entities[i].show = true;
                    }
                    return;
                }
                Cesium.GeoJsonDataSource.load(url, {
                    clampToGround: true
                }).then(function (dataSource) {
                    var entities = dataSource.entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        var entity = entities[i];
                        var position = entity.position._value;
                        // var cartographic = Cesium.Cartographic.fromCartesian(position);
                        // var longitude = Cesium.Math.toDegrees(cartographic.longitude);
                        // var latitude = Cesium.Math.toDegrees(cartographic.latitude);
                        // var height = viewer.scene.sampleHeight(new Cesium.Cartographic(position.x, position.y));
                        // var position = entity.position.getValue(Cesium.JulianDate.now());
                        //entity.position = viewer.scene.clampToHeight(position);
                        // entity.position = Cesium.Cartesian3.fromDegreesArrayHeights([longitude, latitude, Cesium.Cartographic.fromCartesian(viewer.scene.clampToHeight(position)).height + 2])[0];
                        entity.billboard = undefined;
                        entity.point = {
                            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                            pixelSize: 5,
                            color: Cesium.Color.YELLOW.withAlpha(1),
                            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, labelDistance)
                        }
                        entity.label = {
                            text: entity._properties.getValue("")[labelField],
                            font: labelFont,
                            fillColor: !labelColor ? Cesium.Color.WHITE : Cesium.Color.fromCssColorString(labelColor),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            showBackground: !labelBackground ? false : true,
                            backgroundColor: !labelBackground ? Cesium.Color.GREEN : Cesium.Color.fromCssColorString(labelBackground),
                            backgroundPadding: new Cesium.Cartesian2(3, 3),
                            pixelOffset: new Cesium.Cartesian2(0, labelHeight),
                            //pixelOffset: new Cesium.Cartesian2(0, 0),
                            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, labelDistance),
                            outlineColor: outlineColor ? Cesium.Color.fromCssColorString(outlineColor) : Cesium.Color.BLACK,
                            outline: true,
                            outlineWidth: outlineWidth ? outlineWidth : 2,
                            // disableDepthTestDistance: 200,
                            // eyeOffset: new Cesium.ConstantProperty(new Cesium.Cartesian3(0, 0, -10)),
                            //horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            //verticalOrigin: Cesium.VerticalOrigin.CENTER,
                            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                        };
                    }
                    curlayer = viewer.dataSources.add(dataSource);
                    cesium.layer3DList[id] = dataSource;
                });
                break;
            case 12: //geoJson-polygon
                if (cesium.layer3DList[id]) {
                    var entities = cesium.layer3DList[id].entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        entities[i].show = true;
                    }
                    return;
                }
                Cesium.GeoJsonDataSource.load(url).then(function (dataSource) {
                    var entities = dataSource.entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        var entity = entities[i];
                        entity.polygon.fillmaterial = Cesium.Color.RED.withAlpha(0.5);
                        entity.polygon.material = Cesium.Color.BLACK.withAlpha(0.7);
                        entity.polygon.outline = true;
                        entity.polygon.outlineColor = Cesium.Color.BLUE.withAlpha(0.7);
                        entity.polygon.outlineWidth = 3.0;
                        entity.clampToS3M = true;
                        // entity.polygon.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND;

                        // var polyPositions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
                        // var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
                        // polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
                        // entity.position = polyCenter;
                        // entity.label = {
                        //     text: entity._properties.getValue("")["代码"],
                        //     color: Cesium.Color.fromCssColorString('#fff'),
                        //     font: 'normal 20px MicroSoft YaHei',
                        //     showBackground: false,
                        //     scale: 0.5,
                        //     disableDepthTestDistance: 200,
                        //     horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10.0, 100000.0),
                        //     verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        //     // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                        // };
                    }
                    curlayer = viewer.dataSources.add(dataSource);
                    cesium.layer3DList[id] = dataSource;
                });
                break;
            case 13: //geoJson-polyline
                if (cesium.layer3DList[id]) {
                    var entities = cesium.layer3DList[id].entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        entities[i].show = true;
                    }
                    return;
                }
                Cesium.GeoJsonDataSource.load(url).then(function (dataSource) {
                    var entities = dataSource.entities.values;
                    for (var i = 0; i < entities.length; i++) {
                        var entity = entities[i];
                        entity.polyline.width = 10;
                        entity.polyline.heightReference = Cesium.HeightReference.RELATIVE_TO_GROUND;
                        entity.polyline.clampToGround = true;
                        entity.polyline.material = new Cesium.PolylineGlowMaterialProperty({
                            glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
                            color: Cesium.Color.YELLOW.withAlpha(1)
                        })
                        entity.polyline.classificationType = Cesium.ClassificationType.CESIUM_3D_TILE;
                    }
                    curlayer = viewer.dataSources.add(dataSource);
                    cesium.layer3DList[id] = dataSource;
                });
                break;
            case 14: //bilProvider
                var curlayer = new InfoCesiumTerrainProvider({
                    url: url,
                    //ellipsoid: Cesium.Ellipsoid.WGS84
                    //ellipsoid: Cesium.Ellipsoid.MOON
                });
                viewer.scene.terrainProvider = curlayer;
                break;
            case 15: //supermap iserver
                if (cesium.layer3DList[id]) {
                    cesium.layer3DList[id].visible = true;
                    return
                }
                var promise = viewer.scene.open(url);
                Cesium.when(promise, function (layers) {
                    var layer = viewer.scene.layers.find('Config');
                    curlayer = layer;
                    cesium.layer3DList[id] = curlayer;
                });
                break;
            case 16:
                if (cesium.layer3DList[id]) {
                    cesium.layer3DList[id].show = true;
                    return
                }
                var curlayer;
                if (x && y) {
                    var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
                        Cesium.Cartesian3.fromDegrees(parseFloat(x), parseFloat(y), distance ? distance : 1.0)); //gltf数据加载位置
                    curlayer = viewer.scene.primitives.add(Cesium.Model.fromGltf({
                        url: url, //如果为bgltf则为.bgltf
                        modelMatrix: modelMatrix
                        //scale : 3.0     //放大倍数
                    }));
                } else {
                    curlayer = viewer.scene.primitives.add(Cesium.Model.fromGltf({
                        url: url
                    }));
                }

                var m = curlayer.modelMatrix;
                //构建一个三阶旋转矩阵。模型旋转一定的角度，fromRotation[Z]来控制旋转轴，toRadians()为旋转角度，转为弧度再参与运算
                var m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90));

                //矩阵计算
                Cesium.Matrix4.multiplyByMatrix3(m, m1, m);
                //将计算结果再赋值给modelMatrix
                curlayer.modelMatrix = m;
                break;
            default: //ArcGisMapServerImageryProvider
                var curlayer = layers.addImageryProvider(new Cesium.ArcGisMapServerImageryProvider({
                    proxy: new Cesium.DefaultProxy(proxyUrl),
                    url: url,
                    layers: layerid,
                    enablePickFeatures: false
                }), layerindex);
                break;
        }
        if (curlayer)
            cesium.layer3DList[id] = curlayer;
    }
    document.onclick = function () {
        $("#layerBar-main-form").click(function (e) {
            e.stopPropagation();
        })
        $("#ztreecontent").click(function (e) {
            e.stopPropagation();
        });
        $(document).click(function (e) {
            if (e.target.parentElement && e.target.parentElement.id != "rMenu") {
                var lyTreeLists = document.getElementById("LayerTree-main-form-fixed");
                if (lyTreeLists.title != "取消固定") {
                    $("#ztreecontent").hide();
                    $("#rMenu").hide();
                }
            }
            e.stopPropagation();
        });
    };
}

//固定图标
$('#LayerTree-main-form-fixed').click(function () {
    layerControlWindowFixed();
})
//关闭
$('#LayerTree-main-form-closebutton').click(function () {
    CloseLayerDlg("ztreecontent")
})
var layerControlWindowIsFixed = false;

function layerControlWindowFixed() {
    if (layerControlWindowIsFixed) {
        $("#LayerTree-main-form-fixed").removeClass();
        $("#LayerTree-main-form-fixed").addClass("LayerTree-main-form-fixed");
        $("#LayerTree-main-form-fixed").attr("title", "固定");
    } else {
        $("#LayerTree-main-form-fixed").removeClass();
        $("#LayerTree-main-form-fixed").addClass("LayerTree-main-form-fixed-lock");
        $("#LayerTree-main-form-fixed").attr("title", "取消固定");
    }
    //layerControlFixed(layerControlWindowIsFixed);
    layerControlWindowIsFixed = !layerControlWindowIsFixed;
}

function CloseLayerDlg(id) {
    this.fixed = true;
    layerControlWindowIsFixed = true;
    if (document.getElementById(id).style.display != "none") {
        $("#" + id).hide();
    }
}

// 在ztree上的右击事件
function OnRightClick(event, treeId, treeNode) {
    if (treeNode && treeNode.checked && event.target.tagName.toLowerCase() == "span" && treeNode.pId != 0 && treeNode.transparent) {
        showRMenu("root", event.clientX, event.clientY, treeNode.id, treeNode.type);
    }
    // if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
    //     showRMenu("root", event.clientX, event.clientY);
    // } else if (treeNode && !treeNode.noR) {
    //     showRMenu("node", event.clientX, event.clientY);
    // }
    event.stopPropagation();
}
//显示右键菜单
function showRMenu(type, x, y, layerId, layerType) {
    $("#rMenu").show();
    $("#rMenu ul").show();
    $("#transparentHandle").attr("layerId", layerId);
    $("#transparentHandle").attr("layerType", layerType);
    $("#flyToLayerHandle").attr("layerId", layerId);
    $("#flyToLayerHandle").attr("layerType", layerType);
    $("#rMenu").css({ "top": y + "px", "left": x + "px", "visibility": "visible" }); //设置右键菜单的位置、可见
    $("body").bind("mousedown", onBodyMouseDown);
}
//隐藏右键菜单
function hideRMenu() {
    if (rMenu) $("#rMenu").css({ "visibility": "hidden" }); //设置右键菜单不可见
    $("body").unbind("mousedown", onBodyMouseDown);
}
//鼠标按下事件
function onBodyMouseDown(event) {
    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
        $("#rMenu").css({ "visibility": "hidden" });
    }
    event.stopPropagation();
}


/**
 * 设置图层透明度
 * @param {*} e //zTree node
 */
function changeLayerTransparent(id, type, value) {
    //var id = parseInt(e.target.id.split("_")[1]);
    var layer = cesium.layer3DList[id];
    //var type = parseInt(e.target.attributes.layertype.value);
    if (layer) {
        //var transparent = parseInt(e.target.value) / 100;
        switch (type) {
            case 0:
            case 4:
            case 8:
            case 5:
                layer.alpha = value;
                break;
            case 10:
                layer.style = new Cesium.Cesium3DTileStyle({
                    color: "color('rgba(255,255,255," + value + ")')",
                });
            case 16:
                layer.color = Cesium.Color.fromBytes(255, 255, 255, 255 * value)
                break;
            default:
                break;
        }
        layerTransparent[id] = value;
    }
}

/**
 * 缩放到图层
 * @param {*} 
 */
function flyToLayer(layerId, layerType) {
    layerId = parseInt(layerId);
    layerType = parseInt(layerType);
    var layer = cesium.layer3DList[layerId];
    if (layer) {
        switch (layerType) {
            case 0:
            case 4:
            case 8:
            case 5:
                //viewer.flyTo(layer.imageryProvider.rectangle);
                viewer.camera.flyTo({
                    destination: layer.imageryProvider.rectangle,
                    orientation: {
                        heading: Cesium.Math.toRadians(0.0),
                        pitch: Cesium.Math.toRadians(-25.0),
                        roll: 0.0
                    }
                });
                break;
            case 10:
            case 15:
            case 16:
                viewer.zoomTo(layer);
                break;
            default:
                break;
        }
    }
}